package com.rabbiter.si.service;

import com.rabbiter.si.common.ExcelUtils;
import com.rabbiter.si.entity.ImportResult;
import com.rabbiter.si.entity.StudentCourseTeacher;
import com.rabbiter.si.mapper.StudentCourseTeacherMapper;
import com.rabbiter.si.mapper.StudentGradeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
@Slf4j
public class GradeService {
    @Autowired
    private StudentGradeMapper sctMapper;

    // 导入学生课程教师信息
    @Transactional
    public ImportResult importGrades(MultipartFile file) {
        ImportResult result = new ImportResult();

        try {
            // 解析Excel文件
            List<StudentCourseTeacher> sctList = ExcelUtils.importFromExcel(file.getInputStream());

            // 数据校验与导入
            for (StudentCourseTeacher sct : sctList) {
                // 基础校验
                if (sct.getGrade() == null || sct.getGrade() < 0 || sct.getGrade() > 100) {
                    result.addError("成绩无效: 学生ID=" + sct.getSid() + ", 课程ID=" + sct.getCid());
                    continue;
                }

                // 检查学生ID、课程ID和教师ID是否为空
                if (sct.getSid() == null || sct.getCid() == null || sct.getTid() == null) {
                    result.addError("学生ID、课程ID或教师ID为空: 学生ID=" + sct.getSid() + ", 课程ID=" + sct.getCid());
                    continue;
                }

                // 检查记录是否存在（根据学生ID、课程ID、学期判断唯一性）
                int count = sctMapper.countByUniqueKey(sct.getSctid());
                System.out.println(count);
                if (count >0) {
                    // 更新现有记录
                    int updateResult = sctMapper.update(sct);

                    if (updateResult > 0) {
                        result.incrementUpdated();
                    } else {
                        result.addError("更新失败: 学生ID=" + sct.getSid() + ", 课程ID=" + sct.getCid());
                    }
                } else {
                    // 插入新记录
                    int insertResult = sctMapper.insert(sct);

                    if (insertResult > 0) {
                        result.incrementAdded();
                    } else {
                        result.addError("插入失败: 学生ID=" + sct.getSid() + ", 课程ID=" + sct.getCid());
                    }
                }
            }
        } catch (Exception e) {
            result.addError("导入过程发生异常: " + e.getMessage());
            log.error("学生课程教师信息导入异常", e);
        }

        return result;
    }

    // 获取所有学生课程教师信息
    public List<StudentCourseTeacher> getAllStudentCourseTeacher() {
        return sctMapper.selectAll();
    }
}